"use strict";
var timer;
var dataGridObj = {
    $dg: undefined,
    init: function () {
        var total = 0;
        var pageSize = 20;
        var pageNum = 1;
        if (this.$dg == undefined) {
            // 设置table选择器，用来生成datagrid
            this.$dg = $('#dataGridTable');
        }
        if (this.$dg.length > 0) {
            this.$dg.datagrid({
                // 响应式布局
                url:contextPath+'/console/host/loadHostByPage?pageNum=1&pageSize='+pageSize,
                loadMsg: '加载中...',
                fit: true,
                columns: [[
                    {field:'id',title:'主机ID',width:'5%',align:'center',hidden:true},
                    {field:'hostName',title:'主机名称',width:'15%',align:'center'},
                    {field:'hostIp',title:'主机IP',width:'10%',align:'center'},
                    {field:'hostPort',title:'主机端口',width:'10%',align:'center'},
                    {field:'agentPort',title:'监控程序端口',width:'10%',align:'center'},
                    {field:'hostStatus',title:'是否启用',width:'10%',align:'center',
                        formatter: function (value, row, index) {
                            return '<input id="'+row.hostCode+'" />';
                        }
                    },
                    {field:'hostDesc',title:'主机描述',width:'15%',align:'center'},
                ]],
                rownumbers: true,
                rownumberWidth: 70,
                singleSelect: true,
                emptyMsg:'暂无数据',
                pagination:true,
                pageSize:pageSize,
                pageList:[5,10,20,40,80],
                toolbar: [{
                    id:"easyuiAddBtn",
                    text: '新增',
                    iconCls: 'icon-add',
                    plain:true,
                    handler: function () {
                        dataGridObj.goAdd();
                    }
                },{
                    id:"easyuiUptBtn",
                    text: '编辑',
                    iconCls: 'icon-edit',
                    plain:true,
                    handler: function () {
                        dataGridObj.goUpdate();
                    }
                },{
                    id:"easyuiDelBtn",
                    text: '删除',
                    iconCls: 'icon-remove',
                    plain:true,
                    handler: function () {
                        dataGridObj.doDelete();
                    }
                }],
                onSelect:function(index, row){
                    if(row){
                        if(row.hostStatus=="0"){
                            $("#upOrShutdown").find(".l-btn-text").text("启用")
                        }else{
                            $("#upOrShutdown").find(".l-btn-text").text("停用")
                        }
                    }
                },
                onLoadSuccess:function (data) {
                    total = dataGridObj.$dg.datagrid('getData').total;
                    var pager = dataGridObj.$dg.datagrid('getPager');
                    pager.pagination({
                        onSelectPage: function (pageNumber, size) {
                            pageSize = size;
                            pageNum = pageNumber == 0 ?1:pageNumber;
                            var url = contextPath+'/console/host/loadHostByPage?pageSize='+size+'&pageNum='+pageNum;
                            $.get(
                                url,
                                {},
                                function (data) {

                                    dataGridObj.$dg.datagrid('loadData', data);
                                },
                                'json'
                            );

                        }
                    });
                    //判断运维用户是否有读写权限，开关工具栏功能按钮
                    toolbarSwitch();
                    data.rows.forEach(function(value, index, array) {
                        renderSwitchBtn(value);
                    });
                }
            });
            // 重新赋值：获取渲染后的datagrid
            this.$dg = $('#dataGridTable');
            // 渲染成功，返回true
            return true;
        }
        return false;
    },
    // 新增主机，调Dialog打开方法，并且可编辑
    goAdd: function () {
        dialogObj.openAdd(contextPath + '/console/host/add');
        $('#hostPort').textbox('setValue', 22);
        $('#agentPort').textbox('setValue', 9009);
        $('#hostStatus').combobox('setValue', 1);
        $('#hostType').combobox('setValue',1);
        $('#hostCode').textbox('readonly',false);
    },
    // 修改主机，调Dialog打开方法，并且可编辑
    goUpdate: function () {
        dialogObj.openUpdate(this.$dg.datagrid('getSelected'),contextPath + '/console/host/update');
        $('#hostCode').textbox('readonly',true);
    },
    // 删除主机
    doDelete: function () {
        // 获取选中的行
        var row = this.$dg.datagrid('getSelected');
        if (row) {
            apexLayer.Confirm("您确认删除主机吗？",
                "删除主机",
                "确认",
                "取消",
                function () {
                    Ajax({
                        url: contextPath + "/console/host/delete",
                        isMask: true,
                        data: {
                            "id": row.id
                        },
                        success: function (data) {
                            if (data.code>0) {
                                apexLayer.Msg(data.note, 1000, function () {
                                    dataGridObj.$dg.datagrid("reload");
                                });
                            } else {
                                apexLayer.Error("删除失败:" + data.note);
                            }
                        }
                    });
                }
            );
        } else {
            apexLayer.Warn('请先选择一条记录，才能进行删除操作！');
        }
    }
};

$(function () {
    dataGridObj.init();
    dialogObj.init("add-dlg","dataForm");
    // 渲染Dialog
    $('#add-dlg').dialog({
        width: 600,
        height: 'auto',
        closed: true,
        cache: false,
        modal: true,
        shadow: false,
        buttons: [{
            text:'测试',
            iconCls:'icon-large-smartart',
            handler: function () {
                connectTest();
            }
        },{
            text: '保存',
            iconCls: 'icon-save',
            handler: function () {
                dialogObj.submiHandler("dataGridTable");
            }
        }],
        onClose: function () {
            // 还原Dialog
            dialogObj.reset();
        }
    });
    // var ss = "root123";
    // var key = "apexsoft";
    // alert(encryptByDES(ss,key));
});

//加密
function encryptByDES(message, key) {
    var keyHex = CryptoJS.enc.Utf8.parse(key);
    var encrypted = CryptoJS.DES.encrypt(message, keyHex, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });
    return encrypted.toString();
}
//解密
function decryptByDES(ciphertext, key) {
    var keyHex = CryptoJS.enc.Utf8.parse(key);
    var decrypted = CryptoJS.DES.decrypt({
        ciphertext: CryptoJS.enc.Base64.parse(ciphertext)
    }, keyHex, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });
    return decrypted.toString(CryptoJS.enc.Utf8);
}

//测试连接
function connectTest() {
    if (!$("#dataForm").form('validate')) {
        $.messager.progress('close');
        return false;
    }
    var userName = $("#userName").val();
    var userPwd = $("#userPwd").val();
    var hostIp = $("#hostIp").val();
    var hostPort = $("#hostPort").val();
    Ajax({
        url: contextPath + "/console/host/hostConnectTest",
        isMask: true,
        timeout: 0,
        data: {
            userName: userName,
            userPwd:userPwd,
            hostIp:hostIp,
            hostPort:hostPort
        },
        success: function (data) {
            if (data.code == 1){
                apexLayer.Msg(data.note);
            }else{
                apexLayer.Error(data.note);
            }
        },
        error: function (xhr, status, error) {
            layer.msg("调用服务失败");
        }
    });
}



function searchByCondition(num,size) {
    var hostName = $("#search_hostName").val();
    var pageNum = num==null||num==undefined?1:num;
    var pageSize = size==null||size==undefined?15:size;
    var url = contextPath+'/console/host/loadHostByPage';
    $.get(
        url,
        {
            hostName:hostName,
            pageNum:pageNum,
            pageSize:pageSize
        },
        function (data) {
            dataGridObj.$dg.datagrid('loadData', data);
        },
        'json'
    );
}
function resetCondition() {
    $('#search_hostName').textbox('setValue', "");
    searchByCondition();
}

//获取主机监控程序运行状态
function getMagentShow() {
    var hostId = "";
    Ajax({
        url: contextPath + "/console/magent/getHostInfo",
        success: function (data) {
            console.log(JSON.stringify(data));
            // var columns = $('#dataGridTable').datagrid("options").columns;
            // var rows = $('#dataGridTable').datagrid("getRows");
            // var selectRow = $('#dataGridTable').datagrid('getSelected'); //选中的行
            // var selectRowHostId = -1;
            // var selectIndex = -1;
            // if (selectRow!=null){
            //     selectRowHostId = selectRow.id;
            // }
            // if (data.code == 1){
            //     for (var i=0;i<rows.length;i++){
            //         var isHas = false;
            //         hostId = rows[i][columns[0][0].field]; //主机ID
            //         if (selectRowHostId == hostId){
            //             selectIndex = i;
            //         }
            //         for (var j =0;j<data.magentShow.length;j++){
            //             var magentHostId = data.magentShow[j].hostId;
            //             if (magentHostId == hostId){
            //                 isHas = true;
            //                 $('#dataGridTable').datagrid('refreshRow',i);
            //                 // if (data.magentShow[j].magentStatus == "1"){
            //                 //     rows[i][columns[0][8].field]="<p class='green'>正常</p>";
            //                 // }
            //                 // if (data.magentShow[j].magentStatus == "0"){
            //                 //     rows[i][columns[0][8].field]="<p class='red'>异常</p>";
            //                 // }
            //                 if (data.magentShow[j].magentHeartbeat == "1"){
            //                     rows[i][columns[0][7].field]="<p class='green'>正常</p>";
            //                 }
            //                 if (data.magentShow[j].magentHeartbeat == "0"){
            //                     rows[i][columns[0][7].field]="<p class='red'>异常</p>";
            //                 }
            //                 $('#dataGridTable').datagrid('refreshRow',i);
            //                 renderSwitchBtn(rows[i]);
            //             }
            //         }
            //         if(!isHas){
            //             rows[i][columns[0][7].field]="<p class=''></p>";
            //             //rows[i][columns[0][9].field]="<p class=''></p>";
            //             $('#dataGridTable').datagrid('refreshRow',i);
            //             renderSwitchBtn(rows[i]);
            //         }
            //     }
            // }else{
            //     for (var i=0;i<rows.length;i++){
            //         hostId = rows[i][columns[0][0].field];
            //         if (selectRowHostId == hostId){
            //             selectIndex = i;
            //         }
            //         rows[i][columns[0][7].field]="<p class='grey'>监控进程未启动</p>";
            //        // rows[i][columns[0][9].field]="<p class='grey'>监控服务未启动</p>";
            //         $('#dataGridTable').datagrid('refreshRow',i);
            //         renderSwitchBtn(rows[i]);
            //     }
            // }
            // if (selectIndex != -1){
            //     $('#dataGridTable').datagrid('selectRow',selectIndex);
            // }
        }
    });
}

function renderSwitchBtn(value){
    $("#"+value.hostCode).switchbutton({
        width:50,
        height:20,
        onText:'ON',
        offText:'OFF',
        checked:!value.hostStatus=="0",
        onChange:function(checked){
            setTimeout(function(){
                var row = dataGridObj.$dg.datagrid('getSelected');
                var rowIndex = dataGridObj.$dg.datagrid('getRowIndex',row);
                row.hostStatus = checked?"1":"0";
                Ajax({
                    url:contextPath+"/console/host/update",
                    data:row,
                    success:function(data){
                        if(data.code>0){
                            dataGridObj.$dg.datagrid("reload");
                        }else{
                            apexLayer.Error(data.note);
                        }
                    }
                });
            },200);
        }
    });
}
